package com.du.algorithm.primary;

import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import javafx.util.Pair;
import lombok.Data;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: shuangdu
 * @date: 2022/1/27
 * @since: 1.8
 */
public class Test {

    private static final ExecutorService FUTURE_EXECUTOR = Executors.newFixedThreadPool(10);

    private static List<Integer> addData() {
        List<Integer> arr = new ArrayList<>();
        int i = 0;
        while (i < 99) {
            arr.add(i);
            i++;
        }
        return arr;
    }

    public static void main(String[] args) throws Exception{
//        List<Integer> arrays = addData();
//        int limit = 10;
//        int page = (arrays.size() + limit - 1) / limit;
//        List<CompletableFuture<Void>> pageContentFutures = new ArrayList<>();
//        for (int i = 1; i <= page; i++) {
//            int right = i * limit ;
//            if (i == page) {
//                right = arrays.size();
//            }
//            List<?> news = arrays.subList((i - 1) * limit, right);
//            // 添加线程任务
//            pageContentFutures.add(
//                    CompletableFuture.runAsync(() -> {
//                        System.out.println("list size: " + news.size());
//                        System.out.println("list : " + Arrays.toString(news.toArray()));
//                    }, FUTURE_EXECUTOR).exceptionally((throwable) -> {
//                        throwable.getStackTrace();
//                        return null;
//                    })
//            );
//        }
//
//        CompletableFuture<Void> all = CompletableFuture.allOf(pageContentFutures.toArray(new CompletableFuture[0]));
//        all.join();
//        System.out.println("执行完成! " + all.isDone());

//        int[] n = new int[100];
//        for (int i=0;i<100;i++) {
//            n[i] = i;
//        }
//
//        for (int c = 0;c<n.length ;c ++) {
//            if (c == n.length - 1) {
//                System.out.println(n[c]);
//            } else {
//                System.out.println(n[c] + " - " + n[c + 1]);
//            }
//        }

        // create
//        String a = "CREATE TABLE `learn_task_record_%s_%s` (\n" +
//                "  `id` bigint(20) NOT NULL COMMENT '学习任务id',\n" +
//                "  `school_id` varchar(32) NOT NULL COMMENT '学校id',\n" +
//                "  `resource_id` varchar(36) NOT NULL COMMENT '资源id',\n" +
//                "  `resource_title` varchar(128) DEFAULT NULL COMMENT '资源title',\n" +
//                "  `share_task_id` varchar(36) NOT NULL COMMENT '分享任务的id',\n" +
//                "  `share_person_id` varchar(32) NOT NULL COMMENT '分享人的id',\n" +
//                "  `share_dest` varchar(16) NOT NULL COMMENT '分享类型',\n" +
//                "  `class_id` varchar(32) DEFAULT NULL COMMENT '学生所在的班级ID',\n" +
//                "  `user_id` varchar(32) NOT NULL COMMENT '用户id',\n" +
//                "  `user_name` varchar(255) NOT NULL COMMENT '用户名称',\n" +
//                "  `subject_code` varchar(4) DEFAULT NULL COMMENT '学科code',\n" +
//                "  `subject_name` varchar(64) DEFAULT NULL COMMENT '学科名称',\n" +
//                "  `extension` tinyint(4) DEFAULT NULL COMMENT '分享资源的文件类型:1-pdf',\n" +
//                "  `use_case` tinyint(4) DEFAULT NULL COMMENT '使用场景',\n" +
//                "  `task_end_time` datetime DEFAULT NULL COMMENT '任务截止时间',\n" +
//                "  `task_submit_time` datetime DEFAULT NULL COMMENT '任务提交时间',\n" +
//                "  `submit_intime` bit(1) DEFAULT NULL COMMENT '是否准时提交',\n" +
//                "  `check_state` bit(1) DEFAULT NULL COMMENT '是否观看',\n" +
//                "  `self_feedback_state` tinyint(4) DEFAULT NULL COMMENT '0-未反馈 1-完全明白 2-基本了解 3-尚未明白',\n" +
//                "  `directory_id` varchar(128) DEFAULT '0000' COMMENT '学习资料所属目录',\n" +
//                "  `is_deleted` bit(1) DEFAULT NULL COMMENT '是否删除',\n" +
//                "  `learn_remind` tinyint(4) DEFAULT '0' COMMENT '学习提醒:0未提醒，1已提醒',\n" +
//                "  `create_time` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',\n" +
//                "  `last_modify` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '最后修改时间',\n" +
//                "  PRIMARY KEY (`id`) USING BTREE,\n" +
//                "  UNIQUE KEY `uniq_user_share_task_id` (`school_id`,`share_task_id`,`user_id`) USING BTREE,\n" +
//                "  KEY `IDX_directory_id` (`directory_id`) USING BTREE,\n" +
//                "  KEY `IDX_share_task_id` (`share_task_id`,`self_feedback_state`) USING BTREE,\n" +
//                "  KEY `IDX_resource_id` (`resource_id`,`user_id`,`is_deleted`) USING BTREE,\n" +
//                "  KEY `IDX_user_subject` (`user_id`,`is_deleted`,`subject_code`,`self_feedback_state`) USING BTREE\n" +
//                ") ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='学习任务表';";
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i<= 18; i++) {
//            for (int n = 2018; n<= 2023; n++) {
//                sb.append(String.format(a, i, n));
//                sb.append("\n");
//                sb.append("\n");
//            }
//        }
//
//        System.out.println(sb);


        // truncate
//        String a = "TRUNCATE TABLE learn_task_2.learn_task_record_%s_%s;";
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i<= 18; i++) {
//            for (int n = 2018; n<= 2022; n++) {
//                sb.append(String.format(a, i, n));
//                sb.append("\n");
//            }
//        }
//
//        System.out.println(sb);

        // insert suc
//        File f = new File("C:\\Users\\shuangdu\\Desktop\\do186.txt");
//        BufferedReader reader = new BufferedReader(new FileReader(f));
//        String temp = null;
//        StringBuilder sb = new StringBuilder();
//        while ((temp = reader.readLine()) != null) {
//            String s = temp.substring(temp.indexOf("suc") + 3).replaceAll(" ", "");
//            String[] nums = s.split("->");
//            if (nums.length > 1) {
//                if (!nums[0].equals(nums[1])) {
//                    sb.append(temp);
//                    sb.append("\n");
//                }
//            }
//
//        }
//        System.out.println(sb);

//        System.out.println(System.currentTimeMillis());


        // insert offset
//        String a = "'20960a13-a9d7-4712-bc53-3bc5cc9e57aa',\n" +
//                "'89a3da67-7247-43f1-a933-1d1b8b118fd9',\n" +
//                "'8db3d878-7fcc-4423-b2d1-0528f01d664d',\n" +
//                "'06df6115-c580-4730-aeda-97aaa68e544c',\n" +
//                "'eca46159-1267-4960-941c-abf360137876',\n" +
//                "'cc5412be-37d8-4596-9b82-1a25627ecc32',\n" +
//                "'3c0cfc2a-1699-4989-ade6-48534e213598',\n" +
//                "'8a848b1e-a17c-4b6f-a086-4bc887055305',\n" +
//                "'5dfb388f-4bf7-4e44-a699-ff54169755bc',\n" +
//                "'fbb00afa-5c17-414d-abae-87a275aea3f0',\n" +
//                "'48916eee-7dc5-4f4a-9c8f-11767dccf7ce',\n" +
//                "'bcd6bda2-58bb-4063-a687-30d6f58c3551',\n" +
//                "'6391e683-1b99-41d2-bfb3-564a38de6fad',\n" +
//                "'0d6de0fd-4884-4909-aac4-e418404fe5dd',\n" +
//                "'daf0d383-7286-4425-a84d-8cf44a46b08c',\n" +
//                "'2d812a57-bfe8-4f61-a839-8c17ece675f2'";
//
//        String[] split = a.split(",");
//        StringBuilder sb = new StringBuilder("INSERT INTO learn_task_migrate_offset(batch_no, offset_id, offset_result, create_time, modify_time) VALUES");
//        for (String b : split) {
//            sb.append("('1646964552168',")
//            .append(b)
//            .append(", 0, NOW(), NOW()),");
//        }
//        System.out.println(sb);

        // delete learnTask
//        String sql = "SELECT COUNT(1) num From learn_task_record_%s WHERE create_time between '2022-04-20' and '2022-05-09' Union all";
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i<18; i++) {
//            sb.append(String.format(sql, i));
//            sb.append("\n");
//        }
//        System.out.println(sb);

//        List<Integer> list = new ArrayList<>();
//        int count = 0;
//        while (count < 1000) {
//            list.add(count++);
//        }
//
//        try {
//            Test.processWhileSubList(Test::doSomething, list, 20);
//
//        } catch (Exception e) {
//            System.out.println("error");
//        }

//        P p = new P();
//        List<String> offShelf = p.offShelf;
//        List<String> onShelf = p.onShelf;
//        offShelf.add("001100325103-301");
//        offShelf.add("001601161205-3698");
//        onShelf.add("001601161205-3699");
//        onShelf.add("01010101-002");
//        onShelf.add("0101010101-412");
//        onShelf.add("01010107-001");
//
//        System.out.println(JSONUtil.toJsonStr(p));


//        System.out.println(todayTtl());


//        String s = "<p><img src=\"https://test.download.cycore.cn/zhkt-cystorage-client/2022/6/16/4/20/7212a76d-8f56-4ae6-9a33-72117b2efc5d.png\"></p>";
//
//        String format = s.replaceAll("(src=\")https://test.download.cycore.cn/zhkt-cystorage-client/2022/6/16/4/20/7212a76d-8f56-4ae6-9a33-72117b2efc5d.png(\")", "");
//
//        System.out.println(format);


//        String a = "a,b,c,d";
//        String[] split = a.split(",");
//        List<String> list = Arrays.asList(split);
//        String d = list.stream().filter(i -> i.equals("e")).findFirst().orElse(null);
//        System.out.println(d);

        // 时间区域
//        List<String> duringDate = DateUtil.rangeToList(
//                DateUtil.parseDate("2022-08-02"),
//                DateUtil.parseDate("2022-08-21"),
//                DateField.DAY_OF_MONTH
//        ).stream().map(i -> i.toString(DatePattern.NORM_DATE_FORMAT)).collect(Collectors.toList());
//
//        duringDate.forEach(s -> System.out.println(s));

//        System.out.println(UUID.randomUUID().toString().length());
//
//        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        long s = System.currentTimeMillis();
//        Pair<Long, Long> pair = getTimeCycle();
//        System.out.println("waste time: " + (System.currentTimeMillis() - s));
//        System.out.println("start:"+ f.format(new Date(pair.getKey())) + " end:"+ f.format(new Date(pair.getValue())));


        String sql = "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '儿童隐私保护政策', 'p_qzk5_2', '/pages/student/childPrivacyPolicy.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 2, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '讯飞智慧教育通行证账号用户协议', 'p_qzk5_2', '/pages/student/eduUserAgreement.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 8, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '隐私政策', 'p_qzk5_2', '/pages/student/privacyPolicy-zy.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 5, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '个人信息收集清单', 'p_qzk5_2', '/pages/student/personalInformation.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 1, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '讯飞智慧教育通行证账号隐私政策', 'p_qzk5_2', '/pages/student/eduPrivacyPolicy.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 7, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '设备权限清单', 'p_qzk5_2', '/pages/student/devicePermissions.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 6, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '第三方共享与SDK清单', 'p_qzk5_2', '/pages/student/SDK.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 3, '7.0', b'0', '%s', '%s', '');\n" + "INSERT INTO `smart_class`.`agreement_list_record`(`id`, `agreement_title`, `device_type`, `location`, `package_url`, `package_md5`, `num`, `version`, `is_deleted`, `create_time`, `modify_time`, `machine_type`) VALUES ('%s', '用户协议', 'p_qzk5_2', '/pages/student/userAgreement.html', 'https://edu-download.cycore.cn/aidp_store_07f7ef/20241108/d7ebe554f8fb422daa4b0c3160ff210b/c74d526c-e7cf-4fc9-b792-b92a6a363537.zip', '79749cc53927663d354d4d5088576d6d', 4, '7.0', b'0', '%s', '%s', '');\n";
        String[] sqls = sql.split(";");
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = dateFormat.format(new Date());
        for (String st : sqls) {
            sb.append(String.format(st, UUID.randomUUID(), date, date)).append(";");
        }
        System.out.println(sb);


    }


    public static <T> List<List<T>> splitList(List<T> list, int sublistSize) {
        List<List<T>> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i += sublistSize) {
            result.add(
                    new ArrayList<>(list.subList(i, Math.min(i + sublistSize, list.size())))
            );
        }
        return result;
    }

    private static Pair<Long, Long> getTimeCycle() {
        // 2024-07-01 00:30:01
        long lastTime = 1719937800001L;
//        long nowTime = System.currentTimeMillis();
        long nowTime = 1719765000000L;
        // 计算周期
        long q = 2 * 86400000L;
        long n = (long) Math.ceil((nowTime - lastTime) / (double)q);
        return new Pair<>(lastTime + ((n-1) * q), lastTime + (n * q));
//        long t = (nowTime - lastTime) - n * q ;
//        if (t < 0) {
//            return new Pair<>(lastTime + (n * q), nowTime);
//        } else {
//            return new Pair<>(lastTime + (n * q), lastTime + (n+1) *q);
//        }
    }


    public static String encodeChineseInUrl(String url) throws UnsupportedEncodingException {
        Pattern pattern = Pattern.compile("[^\\x00-\\xff]");
        Matcher matcher = pattern.matcher(url);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String chineseChar = matcher.group();
            String encodedChar = URLEncoder.encode(chineseChar, "UTF-8");
            matcher.appendReplacement(sb, encodedChar);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 格式化昨天日期
     * @param datePattern
     * @return
     */
    public static String formatLastDate(String datePattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
        return sdf.format(addDay(-1));
    }

    public static Date addDay(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,days);
        return calendar.getTime();
    }

    public static List<String> monthDim(String start, String end) {
        List<String> monthDim = new ArrayList<>();
        Calendar startCalendar = DateUtil.parseDate(start).toCalendar();
        startCalendar.set(Calendar.DAY_OF_MONTH, 1);
        Calendar endCalendar = DateUtil.parseDate(end).toCalendar();
        while (startCalendar.compareTo(endCalendar) <= 0) {
            String month = DateUtil.format(startCalendar.getTime(), DatePattern.NORM_MONTH_PATTERN);
            monthDim.add(month);
            startCalendar.add(Calendar.MONTH, 1);
        }

        return monthDim;
    }

    public static List<Integer> getData(int count) {
        List<Integer> arr = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            arr.add(i);
        }
        return arr;
    }

    public static boolean hasVal(int[] arr, int val) {
        return Arrays.stream(arr).anyMatch(v -> v == val);
    }

    public static long todayTtl() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);
        instance.set(Calendar.HOUR_OF_DAY, 0);
        instance.set(Calendar.MINUTE, 0);
        instance.set(Calendar.SECOND, 0);
        instance.set(Calendar.MILLISECOND, 0);
        return instance.getTimeInMillis() - System.currentTimeMillis();
    }

    @Data
    public static class P {
        private List<String> onShelf = new ArrayList<>();

        private List<String> offShelf = new ArrayList<>();
    }

    private static ConcurrentHashMap<Long, Long[]> cache = new ConcurrentHashMap<>(1, 1.0f);

    public static Long[] makeRange(Date now) {
        System.out.println("生成取值范围...");
        Long[] range = new Long[2];
        int year = Calendar.getInstance().get(Calendar.YEAR);
        Date limit = limitStart(year);

        if (now.getTime() >= limit.getTime()) {
            // 跨下个学期
            range[0] = limitStart(year - 2).getTime();
            range[1] = limitEnd(year + 1).getTime();
        } else {
            // 当前学年
            range[0] = limitStart(year - 3).getTime();
            range[1] = limitEnd(year).getTime();
        }
        return range;
    }

    public static Date limitStart(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.SEPTEMBER);
        c.set(Calendar.DATE, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    public static Date limitEnd(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.AUGUST);
        c.set(Calendar.DATE, 31);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MILLISECOND, 999);
        return c.getTime();
    }


    public static Date addMonth(Date date, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(2, month);
        return c.getTime();
    }

    public static <T> void doSomething(List<T> l) {
        try {

        } catch (Exception e) {
            System.out.println("error");
        }
    }

    public static <T> void processWhileSubList(Consumer<List<T>> func, List<T> arrays, int limit){
        if(arrays == null || arrays.isEmpty()){
            return;
        }
        int page = (arrays.size() + limit - 1) / limit;
        for (int i = 1; i <= page; i++) {
            int right = i * limit ;
            if (i == page) {
                right = arrays.size();
            }
            List<T> news = arrays.subList((i - 1) * limit, right);
            func.accept(news);
        }
    }
    @FunctionalInterface
    public interface SubListFunction<T> {
        void process(List<T> lists);
    }
}
